/* 
 * Copyright (C) 2013 hakan.johansson@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
var numberOfImages;
var numberOfAlbums = 0;
var album;
var slideshowActive = false;
var intervalID
var fadeInSpeed = 400
var fadeOutSpeed = 300
var slideShowTimeout = 5000
var pictureInView = false;
var keyNavEnabled = true;
var modalInfoCallback = 0;
var albumEditIndex = -1;



var oneAlbum = ['<div id="album">',
               '  <div id="thumb">',
               '    <a href="#{0}">',
               '    <img src="{1}"></a>',
               '  </div>',
               '  <div id="description">',
               '    <h4><a href="#{2}">{3}</a></h4>',
               '    <a href="#{2b}" id=descriptiontext{4}>{5}</a>',
               '    <br/><br/><div style="display:none;" class=editLinkDiv><a onClick=editAlbumDescription({7},{8})> Edit </a></div>',
               '    </div>',
               '  <div id="nbr_of_images">{6}</div>',
               '</div>'].join("\n")

var oneImage = ["<div id='imageContainer'>",
                  '<div id="sivMenu">',
                  "<ul>",
                    //"<li id='name'> </li>",
                    "<li><img id='closeBtn' src='res/close.png'></img></li>",
                    "<li><img id='nextBtn' src='res/next.png'></img><img id='prevBtn' src='res/prev.png'></img></li>",
                    "<li><img id='playBtn' src='res/play.png'></img></li>",
                    //"<li><img id='infoBtn' src='res/info.png'></img></li>",
                    "<li><img id='fullScreenBtn' src='res/fullscreen.png'></img></li>",
                    "</ul>",
                  '</div>',
                  "<img id=theimage src=>",
                  "<p id='imagedescription'></p>",
                  "<div class=editLinkDiv style='display:none;'><a onClick=editImageDescription()> Edit </a></div>",
               "</div>"].join("\n")

$(document).ready(function() {
  jQuery.fn.center = function () {
    this.css("position","fixed");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2)));
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2)));
    return this;
  }

  // Use this to avoid right click menu
  //$(document).bind("contextmenu",function(e){
  //  return false;
  //});

  $(window).resize(function(){
    $("#imageContainer").center();
    $("#header").css("width",$(window).width() - 70);
  });
  
  $("body").keydown(function(e){
    if(pictureInView && keyNavEnabled) {
        // left arrow
        if ((e.keyCode || e.which) == 37) {   
            if(slideshowActive) {
                startStopSlideshow();
            }
            getPreviousImage();
        }
        // right arrow
        if ((e.keyCode || e.which) == 39) {
            if(slideshowActive) {
                startStopSlideshow();
            }
            getNextImage();
        }
        // esc
        if ((e.keyCode || e.which) == 27) {
            if(slideshowActive) {
                startStopSlideshow();
            }
            closeSivImage();
        }
    }
    });

   documentReady(); 
});

function documentReady() {
    album = window.location.href.split("#")[1];
    if(album) {
      $("#headerTitle").html(decodeURI(album));
      $("#backBtn").show();
    } else {
      $("#headerTitle").html("Webalbum");
      $("#backBtn").hide();
    }

    $("#backBtn").click(function(){goBack();});
    $("#header").css("width", $(window).width() - 70);
    $("#loginBox").submit(function(){login();return false;});

    // Make sure all methods that create the UI is run before we check if we are logged in since it changes the UI. (so it has to be there)
    $.when(loadPreviewImages(), getNumberOfImages(), loadSubAlbums()).done(function(){checkIfLoggedIn();});
    registerToUriChanges();
}

function checkIfLoggedIn() {
  console.log("JS::getLoggedInStatus");
  $.get("wsgi",
  {
    getLoggedInStatus: 1
  },
  function(data,status){
    console.log("JS::getLoggedInStatus: " + data);
    if(data == "true") {
       loggedIn = true;
       $("#login").hide();
       $("#logout").show();
       $(".editLinkDiv").show()
    } else {
       loggedIn = false;
       $("#login").show();
       $("#logout").hide();
       $(".editLinkDiv").hide()
    }
  });
}

function goBack() {
  path = window.location.href.split("#")[0];
  albumPath = window.location.href.split("#")[1];
  if(albumPath.lastIndexOf("/") != -1) {
    newAlbumPath = albumPath.slice(0,albumPath.lastIndexOf("/"));
    window.location.href = path + "#" + newAlbumPath;
  } else {
    window.location.href = path;
  }
}

function registerToUriChanges() {
  if ("onhashchange" in window) { // event supported?
      window.onhashchange = function () {
          location.reload();
      }
  }
  else { // event not supported:
      var storedHash = window.location.hash;
      window.setInterval(function () {
          if (window.location.hash != storedHash) {
              storedHash = window.location.hash;
              location.reload();
          }
      }, 100);
  }
}

function loadPreviewImages() {
  console.log("JS::loadSubAlbums");
  return $.get("wsgi",
  {
    getPreviewImages: 1,
    albumPath: album
  },
  function(data,status){
    //console.log("JS::loadSubAlbums data: " +data);¨
    var jsonObj = eval('(' + data + ')');
    imgTag = "";
    for(var index in jsonObj) {
      name = jsonObj[index].name
      id = jsonObj[index].imageId
      
      imgTag += "<div id=previewImageFrame><img name='"+name+"' id="+id+" src=wsgi/?getImagePreview=1&albumPath="+album+"&imageId="+id+"></div>"
      
      $("#"+id).hide().fadeIn(1000);
    }
    $(imgTag).appendTo("#previewList");

    $("#previewList img").click(function(e){previewClicked(e);});

  var $container = $('#previewList');
  $container.imagesLoaded( function(){
  $container.masonry({
    itemSelector : '#previewImageFrame',
    isAnimated: true
    });
  });
  });
}


function loadSubAlbums() {
        console.log("JS::loadSubAlbums");
        return $.get("wsgi",
        {
          getSubAlbums: 1,
          albumPath: album
        },
        function(data,status){
          //console.log("JS::loadSubAlbums data: " +data);
          var jsonObj = eval('(' + data + ')');
          content = ''
          for(var index in jsonObj) {
            cwd = jsonObj[index].cwd
            name = jsonObj[index].name
            description = jsonObj[index].description
            numOfImages = jsonObj[index].numberOfImages
            numOfAlbums = jsonObj[index].numberOfAlbums

            //console.log("JS:album.cwd:"+jsonObj[index].cwd);
            cwd = encodeURI(cwd);
            content += oneAlbum
            content = content.replace("{0}", cwd);
            if(numOfImages == 0) {
              content = content.replace("{1}", "res/album_default.png");
            }else {
              content = content.replace("{1}", "wsgi/?getAlbumThumb=1&amp;albumPath="+cwd+"&amp;size=small");
            }
            content = content.replace("{2}", cwd);
            content = content.replace("{2b}", cwd);
            content = content.replace("{3}", name);
            content = content.replace("{4}", index);
            content = content.replace("{5}", description);
            if(numOfImages != 0) {
              content = content.replace("{6}", numOfImages+" images");
            } else if(numOfAlbums != 0) {
              content = content.replace("{6}", numOfAlbums+" albums");
            }

            content = content.replace("{7}", index);
            content = content.replace("{8}", '"'+cwd+'"');

			}
			$(content).appendTo('#albums');
			$('#albums').masonry({
				itemSelector : '#album',
				isAnimated: true
			});
        });
    }

function getNumberOfImages() {
  return $.get("wsgi",
  {
    getNumOfImages: 1,
    albumPath: album
  },
  function(data,status){
    //console.log("JS:getNumberOfImages() data:"+data);
    numberOfImages = parseInt(data);   
    return numberOfImages;
  });
}

function openSivImage(imageID) {
  $(oneImage).insertAfter('#imageId').hide();
  $("#sivMenu").hide();
  $("#theimage").hide();
  $("#shadeBox").fadeIn(fadeInSpeed);
  $("#imageContainer").fadeIn(fadeInSpeed);


  $("#theimage").click(function(){if(slideshowActive) {startStopSlideshow();}getNextImage();});
  $("#theimage").load(function(){imgLoad(this)});
  $("#closeBtn").click(function(){if(slideshowActive) {startStopSlideshow();}closeSivImage()});
  $("#prevBtn").click(function(){if(slideshowActive) {startStopSlideshow();}getPreviousImage();});
  $("#nextBtn").click(function(){if(slideshowActive) {startStopSlideshow();}getNextImage();});
  $("#playBtn").click(function(){startStopSlideshow();});
  $("#infoBtn").click(function(){infoButtonClicked();});
  $("#fullScreenBtn").click(function(){fullScreenButtonClicked();});
  // Set the new URL first after the fade in has completed so that the user gets 
  // to see the fade animation even when loadtime is faster than fadein time
  setTimeout(function(){updateFloatingWindowImage(imageID)}, fadeInSpeed);
  //updateFloatingWindowImage(id);
}

function fullScreenButtonClicked() {
  id = parseInt($("#imageId").val());
  var imgSrc = "wsgi/?getFullscreenImage=1&albumPath="+album+"&imageId="+id+"&width="+-1+"&height="+-1;
  $("#everything").html("<img src='"+imgSrc+"'"+" onclick='location.reload();'</img>")
  
}

function infoButtonClicked() {
  alert("info");
}

function startStopSlideshow() {
  if(slideshowActive==false) {
    $("#playBtn").attr("src","res/pause.png");
    intervalID = setInterval(function(){getNextImage();}, slideShowTimeout);
    slideshowActive = true;
  } else {
    $("#playBtn").attr("src","res/play.png");
    clearInterval(intervalID);
    slideshowActive = false;
  }
}

function updateFloatingWindowImage(id) {
  var imgSrc = "wsgi/?getAlbumImage=1&albumPath="+album+"&imageId="+id;
  $("#theimage").attr("src",imgSrc); 
}

function closeSivImage() {
    pictureInView = false;
    $("#imageContainer").fadeOut(fadeOutSpeed);
    $("#shadeBox").fadeOut(fadeOutSpeed);
}

function getImageInfo(imageId) {
  return $.get("wsgi",
  {
    getImageInfo: 1,
    imageId: imageId,
    albumPath: album
  },
  function(data,status){
    console.log("JS::loadSubAlbums data: " +data);
    var jsonObj = eval('(' + data + ')');
    name = jsonObj.name;
    description = jsonObj.description
    if(description) {
      $("#imagedescription").html(description);
    } else {
      $("#imagedescription").html(name);
    }
    

  });
}

function imgLoad(img) {
    height = parseInt($(window).height()*0.8); //Cover 80% of the screen with fullscreen image
    width = parseInt($(window).width()*0.8); //Cover 80% of the screen with fullscreen image

    $.when(getImageInfo(parseInt($("#imageId").val()))).done(function(){
        $("#sivMenu").fadeIn(fadeInSpeed)
        $("#theimage").fadeIn(fadeInSpeed);
        $("#theimage").css({"height":height});
        $("#theimage").css({"width":"auto"});
        $("#imageContainer").fadeIn(fadeInSpeed);
        $("#imageContainer").css({"height":"auto"});
        $("#imageContainer").css({"width":$("#theimage").width()});

        // If the image is to wide after we have set the max height let the width be the limiting factor
        if($("#theimage").width() > width) {
          $("#theimage").css({"width":width});
          $("#theimage").css({"height":"auto"});
        }
        if($("#imageContainer").width() > width) {
          $("#imageContainer").css({"width":$("#theimage").width()});
          $("#imageContainer").css({'height':'auto'});
        }
        $("#imageContainer").center();
        checkIfLoggedIn();
    });
    
    pictureInView = true;
}

function previewClicked(evt) {
    var imageID = evt.target.id;
    //var name = $("#"+imageId).attr("name");
    $("#imageId").val(imageID);
    openSivImage(imageID);
}

function getPreviousImage() {
  id = parseInt($("#imageId").val());
  if(id == 0) {
    closeSivImage();
  } else {
    newImageId = id-1;
    $("#imageId").val(newImageId);
    var width = $("#imageContainer").width()
    $("#theimage").fadeOut(fadeOutSpeed);
    $("#imageContainer").fadeOut(fadeOutSpeed);
    setTimeout(function(){updateFloatingWindowImage(newImageId)}, fadeOutSpeed-100); //-100 because it takes some time to convert/load the image
    //updateFloatingWindowImage(newImageId);
  }
}

function getNextImage() {
    id = parseInt($("#imageId").val());
    console.log("imageId: "+id+" numberOfImages:"+numberOfImages);
    if(id == numberOfImages-1) {
      closeSivImage();
    } else {
      newImageId = id+1;
      $("#imageId").val(newImageId);
      var width = $("#imageContainer").width()
      $("#theimage").fadeOut(fadeOutSpeed);
      $("#imageContainer").fadeOut(fadeOutSpeed);
      $("#imageContainer").fadeOut(fadeOutSpeed);
      setTimeout(function(){updateFloatingWindowImage(newImageId)}, fadeOutSpeed+100);
      //updateFloatingWindowImage(newImageId);
    }
}

function login() {
  username = $("#username").val();
  password = $("#password").val();
  $.get("wsgi",
  {
    login: 1,
    user:  username,
    pass: password
  },
  function(data,status){
    console.log("JS::login: " + data);
    //location.reload();
    closeLoginBox();
    if(data == "success") {
    } else {
      showInformation("Error: Could not log in. Please check you credentials!", 0);
    }
    checkIfLoggedIn();
  });
}

function logout() {
  $.get("wsgi",
  {
    logout: 1
  },
  function(data,status){
    console.log("JS::logout: " + data);
    checkIfLoggedIn();
  });
}

function editImageDescription() {
  var text = $("#imagedescription").html();
  openEditTextBox(text, 0, saveImageDescription);
}

function saveImageDescription(save) {
  if(save){
    newtext = $("#editText").val();
    albumPath = window.location.href.split("#")[1];
    $.ajax({
      url: "wsgi", 
      data: {"saveImageDescription":1,"text":newtext, "index":$("#imageId").val(), "albumPath":albumPath},
      type: 'get',
      error: function(XMLHttpRequest, textStatus, errorThrown){
          showInformation(XMLHttpRequest.statusText,function(){});
      },
      success: function(data){
        //showInformation(data,0);
        $("#imagedescription").html($("#editText").val());
      }
    });
  }
  $("#editTextBox").hide();
}

function editAlbumDescription(index, cwd) {
  var text = $("#descriptiontext"+index).html();
  albumEditIndex = index;
  $("#shadeBox").css({"opacity":0.5});
  $("#shadeBox").fadeIn(fadeInSpeed);
  openEditTextBox(text, cwd, saveAlbumDescription);
}

function saveAlbumDescription(save) {
  if(save){
    newtext = $("#editText").val();
    cwd = $("#clientdata").html();
    $.ajax({
      url: "wsgi", 
      data: {"saveAlbumDescription":1,"text":newtext, "albumPath":cwd},
      type: 'get',
      error: function(XMLHttpRequest, textStatus, errorThrown){
          showInformation(XMLHttpRequest.statusText,0);
      },
      success: function(data){
        //showInformation(data,0);
        $("#descriptiontext"+albumEditIndex).html($("#editText").val());
        albumEditIndex = -1;}
    });
  }
  $("#shadeBox").fadeOut(fadeOutSpeed);
  $("#editTextBox").hide();
}

function openLoginBox() {
  console.log("JS::openLoginBox");
  keyNavEnabled = false;
  $("#infoBox").hide();
  $("#loginBox").center();
  $("#shadeBox").css({"opacity":0.5});
  $("#shadeBox").fadeIn(fadeInSpeed);
  $("#loginBox").show();
}

function closeLoginBox() {
  keyNavEnabled = true;
  $("#loginBox").hide();
  $("#shadeBox").hide();
}

function showInformation(message, callBack) {
  keyNavEnabled = false;
  modalInfoCallback = callBack;
  $("#infoBox").center();
  //$("#shadeBox").css({"opacity":0.5});
  $("#shadeBox").fadeIn(fadeInSpeed);
  $("#infoText").html(message);
  $("#infoBox").show();
}

function hideInformation(message) {
  keyNavEnabled = true;

  $("#infoBox").hide();
  if(modalInfoCallback) {
    modalInfoCallback();
  } else {
    $("#shadeBox").fadeOut(fadeOutSpeed);
  }
  modalInfoCallback = 0;
}

function openEditTextBox(text, clientdata, saveFunction) {
  modalInfoCallback = saveFunction;
  keyNavEnabled = false;
  $("#editTextBox").center();
  $("#editTextBox textarea").val(text);
  $("#clientdata").html(clientdata);
  $("#editTextBox").show();
}

function closeEditTextBox(save) {
  keyNavEnabled = true;
  if(modalInfoCallback) {
    modalInfoCallback(save);
  } else {
    $("#shadeBox").fadeOut(fadeOutSpeed);
    $("#editTextBox").hide();
  }
  modalInfoCallback = 0;
}

